package com.gitee.zwj;


import com.gitee.zwj.codegen.CalculatorBaseVisitor;
import com.gitee.zwj.codegen.CalculatorParser;
import org.apache.velocity.tools.generic.MathTool;


public class ArithmeticEvalVisitor extends CalculatorBaseVisitor<Number> {

    private final MathTool mathTool = new MathTool();

    //每条规则都对应语法分析器中的一个函数，我们在g4文件中定义了4条规则
    @Override
    public Number visitMulDiv(CalculatorParser.MulDivContext ctx) {
        Object left = visit(ctx.expr(0));
        Object right = visit(ctx.expr(1));
        if (ctx.op.getType() == CalculatorParser.MUL) {
            return mathTool.mul(left, right);
        }
        return mathTool.div(left, right);
    }

    @Override
    public Number visitAddSub(CalculatorParser.AddSubContext ctx) {
        Object left = visit(ctx.expr(0));
        Object right = visit(ctx.expr(1));
        if (ctx.op.getType() == CalculatorParser.Add) {
            return mathTool.add(left, right);
        }
        return mathTool.sub(left, right);
    }

    @Override
    public Number visitNum(CalculatorParser.NumContext ctx) {
        String numberValue = ctx.number().getText();
        if (numberValue.contains(".")) {
            return Float.parseFloat(numberValue);
        }
        return Integer.parseInt(numberValue);
    }

    @Override
    public Number visitParens(CalculatorParser.ParensContext ctx) {
        return visit(ctx.expr());
    }
}
